﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Profile;
using System.Text;
using System.Data;
using Gift.Model;
using Gift.DAL;

namespace WebSite.cn
{
    public partial class account : BasePage
    {
        // Fields
        public string address = "";
        public string carid = "0";
        public string carinfo = "";
        public string CarInfo2Html = string.Empty;
        public string cname = "";
        public string email = "";
        public string phone = "";
        public string post = "";
        public string score1 = "0";
        public string score2 = "0";
        public string score3 = "0";
        public string tel = "";
        public string professionTotalPrice = "0";
        public string shoppingTotalPrice = "0";
        public string accountmoney = "0";
        public string sendDate = DateTime.Now.AddDays(3).ToString("yyyy-MM-dd");
        public string tempOrderCode = "";
        public decimal UserCardTotalPrice = 0;


        readonly MemberAccount theMemberAccount = new MemberAccount();
        readonly DALMember theMember = new DALMember();
        readonly OrderAccount theOrderAccount = new OrderAccount();
        DALInstitution theInstitution = new DALInstitution();


        public string BackHref
        {
            get {
                if (Session["backHref"] != null)
                {
                    return Session["backHref"].ToString() + "&isView=1";
                }
                else
                {
                    return "#";
                }
            }
        }

        // Methods
        private void BuildForm()
        {
            DataTable table;
            if (base.LoginMember != null)
            {
                table = SQLAccess.GreatDs("select membername,tel1,phone,post,address,email from DB_Member where memberid=" + LoginMember.MemberId.ToString() + "").Tables[0];
                if (table.Rows.Count > 0)
                {
                    this.cname = table.Rows[0]["membername"].ToString();
                    this.tel = table.Rows[0]["tel1"].ToString();
                    this.phone = table.Rows[0]["phone"].ToString();
                    this.post = table.Rows[0]["post"].ToString();
                    this.address = table.Rows[0]["address"].ToString();
                    this.email = table.Rows[0]["email"].ToString();
                }
            }
            if (base.Request.QueryString["action"] != null)
            {
                string str3 = re.replace(base.Request.QueryString["carid"]);
                if (re.replace(base.Request.QueryString["action"]) == "edit")
                {
                    string str2 = re.replace(base.Request.Form["car_" + str3 + ""]);
                    table = SQLAccess.GreatDs("select top 1 carid,pronum,price,score from DB_Car where carid=" + str3 + "").Tables[0];
                    if (table.Rows.Count > 0)
                    {
                        SQLAccess.DoSql("update DB_Car set pronum=" + str2 + ",sumprice=" + Convert.ToString((float)(Convert.ToSingle(str2) * Convert.ToSingle(table.Rows[0]["price"]))) + ",sumscore=" + Convert.ToString((float)(Convert.ToSingle(str2) * Convert.ToSingle(table.Rows[0]["score"]))) + " where carid=" + table.Rows[0]["carid"].ToString() + "");
                        base.Response.Write("<script language='javascript'>alert('修改成功!');window.location.href='account.aspx';</script>");
                        base.Response.End();
                    }
                }
                if (re.replace(base.Request.QueryString["action"]) == "del")
                {
                    SQLAccess.DoSql("delete from DB_Car where carid=" + str3 + "");
                    base.Response.Write("<script language='javascript'>alert('删除成功!');window.location.href='account.aspx';</script>");
                    base.Response.End();
                }
            }
                string sTempMemberId = string.Empty;

                 sTempMemberId = LoginMember.MemberId.ToString();

                table = SQLAccess.GreatDs("select DB_Car.carid,DB_Car.pronum,DB_Car.price,DB_Car.sumprice,DB_Car.contents,isnull(DB_Shoppro.proisnew3,0) as proisnew3,"
                                       + " isnull(DB_Shoppro.proisnew2,0) as proisnew2, isnull(DB_Shoppro.proisnew4,0) as proisnew4,"
                                        + " DB_Shoppro.typeid,DB_Shoppro.proname,DB_Shoppro.proprice1,DB_Shoppro.propic2,DB_Shoppro.proid,isnull(institutionId,0) as  institutionId,DB_Shoppro.ProfessionAreaTypeId "
                                         + " from DB_Car inner join DB_Shoppro on DB_Car.productid=DB_Shoppro.proid "
                                         + " where DB_Car.flag=0 and DB_Car.temp=" + sTempMemberId).Tables[0];

                Dictionary<int, DataTable> dicProduct = new Dictionary<int, DataTable>();
                if(table != null && table.Rows.Count>0)
                {
                    DataRow drTemp;
                    foreach(DataRow dr in table.Rows)
                    {
                        if (!dicProduct.Keys.Contains(int.Parse(dr["institutionId"].ToString())))
                        {
                            DataTable dtTemp = table.Clone();
                            dicProduct[int.Parse(dr["institutionId"].ToString())] = dtTemp;
                        }
                        drTemp = dicProduct[int.Parse(dr["institutionId"].ToString())].NewRow();
                        drTemp.ItemArray = dr.ItemArray;
                        dicProduct[int.Parse(dr["institutionId"].ToString())].Rows.Add(drTemp);
                    } 
                }

                int iCount = 0;
                StringBuilder strCardInfo = new StringBuilder();
                StringBuilder strCardInfo2 = new StringBuilder();
                decimal decCurrentCardPrice = UserCardTotalPrice;
                foreach (int iKey in dicProduct.Keys)
                {
                    string sTitleName = theInstitution.GetModel(iKey).Name;
                    if (iCount == 0)
                    {
                        foreach (DataRow row in dicProduct[iKey].Rows)
                        {
                            this.carid = this.carid + "," + row["carid"].ToString();

                            if (row["proisnew2"].ToString() == "True")
                            {
                                professionTotalPrice = string.Format("{0:f}", Convert.ToDecimal(row["sumprice"]) + Convert.ToDecimal(this.professionTotalPrice));
                            }
                            else   if (row["proisnew4"].ToString() == "True")
                            {
                                shoppingTotalPrice = string.Format("{0:f}", Convert.ToDecimal(row["sumprice"]) + Convert.ToDecimal(this.shoppingTotalPrice));
                            }

                            decimal prodUserdPrice = 0;
                            //if(LoginMember != null && LoginMember.UserCardCodeList !
                            if (decCurrentCardPrice - Convert.ToDecimal(row["sumprice"]) > 0)
                            {
                                prodUserdPrice = Convert.ToDecimal(row["sumprice"]);
                            }
                            else
                            {
                                prodUserdPrice = decCurrentCardPrice;
                            }
                            decCurrentCardPrice = decCurrentCardPrice - prodUserdPrice;

                            strCardInfo.Append("<tr>");
                            strCardInfo.Append("<td align='center'><a href='products_details.aspx?pid=" + row["proid"].ToString() + "'><img src='../uploadfile/product/" + row["propic2"].ToString() + "' align='left' border='0'  width='106' /></a></td>");
                            strCardInfo.Append("<td align='left' class='article_content'><a href='products_details.aspx?pid=" + row["proid"].ToString() + "' class='blue'>" + row["proname"].ToString() + "</a><br />" + row["contents"].ToString() + "</td>");
                            if (row["proisnew2"].ToString() == "True")
                            {
                                strCardInfo.Append("<td>兑换专区商品</td>");
                            }
                            else if (row["proisnew4"].ToString() == "True")
                            {
                                strCardInfo.Append("<td>礼品商城商品</td>");
                            }
                            else
                            {
                                strCardInfo.Append("<td></td>");
                            }
                            strCardInfo.Append("<td align='center'>" + string.Format("{0:f}", row["price"]) + " 元 </td>");
                            strCardInfo.Append("<form name='frm" + row["carid"].ToString() + "' action='account.aspx?carid=" + row["carid"].ToString() + "&action=edit' method='post'><td align='center'><input name='car_" + row["carid"].ToString() + "' class='box' size='3' maxlength='5' value='" + row["pronum"].ToString() + "' type='text' />");
                            strCardInfo.Append("&nbsp;&nbsp;<input type=image src='images/delete2.gif' /></td></form>");
                            strCardInfo.Append("<td align='center'>" + string.Format("{0:f}", row["sumprice"]) + " 元 </td>");
                            strCardInfo.Append("<td align='center'><a href=\"javascript:if(confirm('确实要删除吗?')){window.location.href='account.aspx?carid=" + row["carid"].ToString() + "&action=del';}\">删除</a></td>");
                            strCardInfo.Append("</tr>");
                        }
                        this.divTitle.InnerHtml = sTitleName;
                        this.carinfo = strCardInfo.ToString();
                        iCount++;
                    }
                    else
                    {
                        strCardInfo2.Append("<div class=\"CarTitle2\">" + sTitleName + "</div> ");
                        foreach (DataRow row in dicProduct[iKey].Rows)
                        {
                            this.carid = this.carid + "," + row["carid"].ToString();

                            if (row["proisnew2"].ToString() == "True")
                            {
                                professionTotalPrice = string.Format("{0:f}", Convert.ToDecimal(row["sumprice"]) + Convert.ToDecimal(this.professionTotalPrice));
                            }
                            else if (row["proisnew3"].ToString() == "True")
                            {
                                shoppingTotalPrice = string.Format("{0:f}", Convert.ToDecimal(row["sumprice"]) + Convert.ToDecimal(this.shoppingTotalPrice));
                            }

                            decimal prodUserdPrice = 0;
                            if (decCurrentCardPrice - Convert.ToDecimal(row["sumprice"]) > 0)
                            {
                                prodUserdPrice = Convert.ToDecimal(row["sumprice"]);
                            }
                            else
                            {
                                prodUserdPrice = decCurrentCardPrice;
                            }

                            decCurrentCardPrice = decCurrentCardPrice - prodUserdPrice;

                            strCardInfo2.Append(" <table width=\"100%\" border=\"0\" cellspacing=\"0\"  class=\"article_content\" style=\"border-top:0px solid #ff980d; \"><tr>");
                            strCardInfo2.Append("<td width=\"90\" align='center'><a href='products_details.aspx?pid=" + row["proid"].ToString() + "'><img src='../uploadfile/product/" + row["propic2"].ToString() + "' align='left' border='0'  width='106' /></a></td>");
                            strCardInfo2.Append("<td  align='left' class='article_content'><a href='products_details.aspx?pid=" + row["proid"].ToString() + "' class='blue'>" + row["proname"].ToString() + "</a><br />" + row["contents"].ToString() + "</td>");
                            strCardInfo2.Append("<td width=\"90\" align='center'>" + string.Format("{0:f}", row["price"]) + " 元 </td>");
                            strCardInfo2.Append("<form name='frm" + row["carid"].ToString() + "' action='account.aspx?carid=" + row["carid"].ToString() + "&action=edit' method='post'>");
                            strCardInfo2.Append(" <td width=\"90\" align='center'><input name='car_" + row["carid"].ToString() + "' class='box' size='3' maxlength='5' value='" + row["pronum"].ToString() + "' type='text' />");
                            strCardInfo2.Append("&nbsp;&nbsp;<input type=image src='images/delete2.gif' /></td></form>");
                            strCardInfo2.Append("<td width=\"90\" align='center'>" + string.Format("{0:f}", row["sumprice"]) + " 元 </td>");
                            strCardInfo2.Append(string.Format("<td width=\"100\">{0}</td>",prodUserdPrice.ToString()));
                            strCardInfo2.Append("<td width=\"90\" align='center'><a href=\"javascript:if(confirm('确实要删除吗?')){window.location.href='account.aspx?carid=" + row["carid"].ToString() + "&action=del';}\">删除</a></td>");
                            strCardInfo2.Append("</tr> </table>");
                        }
                    }
            }

                if (dicProduct.Keys.Count > 0)
                {
                    this.tempOrderCode = theOrderAccount.GenerateOrderCodeForBefor();
                }
                else
                {
                    this.carinfo = "<tr><td align='center' colspan='6' height=45>您的购物车中无商品</td></tr>";
                }

             
                this.CarInfo2Html = strCardInfo2.ToString();

        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!base.IsPostBack)
            {
                
                string sCardMoney = "0";
                if (LoginMember.UserCardCodeList != null)
                {
                    this.divTopMessage.Visible = true;
                    UserCardTotalPrice = 0;
                    for (int i = 0; i < LoginMember.UserCardCodeList.Count; i++)
                    {
                        UserCardTotalPrice += decimal.Parse(LoginMember.UserCardCodeList[i].UserCardPrice);
                    }
                }
           

                sCardMoney = UserCardTotalPrice.ToString();
                this.GetAccountMoney();
                this.lblMoneyMessage.Text = "您兑换专区余额：" + sCardMoney + ",礼品商城余额：" + accountmoney;

                this.BuildForm();
              
            
            }
        }

        private void GetAccountMoney()
        {
            
            if (base.LoginMember == null)
            {
                accountmoney = "0";
            }
            else
            {
                //decimal dMomey = 0;
                //ds = theMemberAccount.GetListByMemberId(int.Parse(Session["memberid"].ToString()));
                //if (ds != null && ds.Tables.Count > 0)
                //{
                //    foreach (DataRow dr in ds.Tables[0].Rows)
                //    {
                //        dMomey =  dMomey + decimal.Parse( dr["cardprice"].ToString());
                //    }
                //}
                //accountmoney = int.Parse(dMomey.ToString()).ToString();

                //DB_Member oMember;
                //oMember = theMember.GetModel(int.Parse(base.UserMemberId));
                //if (oMember != null)
                //{
                //    accountmoney = oMember.money.ToString();
                //}
                accountmoney = theMemberAccount.GetRemainSumMoney(base.LoginMember.MemberId).ToString();
            }
        }

        protected void lbtnExit_Click(object sender, EventArgs e)
        {
            base.LoginMember.UserCardCodeList = null;
            Response.Redirect("index.aspx");
        }

     

    }
}